<template>
  <div class="flex flex-col h-full">
    <el-form :inline="true" :model="selectProps" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="selectProps.username" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item>
        <el-select v-model="selectProps.status" style="width: 100px">
          <el-option label="全部" value="0" />
          <el-option label="管理员" value="2" />
          <el-option label="普通用户" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect">搜索</el-button>
        <el-button type="danger" @click="deleteUsers">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table class="flex-1 " :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection"  width="55" />
      <el-table-column prop="loginname" label="用户名" width="180" align="center" />
      <el-table-column prop="password" label="密码" width="180" align="center" />
      <el-table-column prop="username" label="姓名" align="center" />
      <el-table-column prop="status" label="角色" width="180" align="center">
        <template #default="scope">
          <div class="mx-auto border border-[#ff7575] rounded-sm text-[#ff7575] w-24 bg-[#ff7575]/50"
            v-if="scope.row.status == 2">管理员</div>
          <div class="mx-auto border border-[#3375b9] rounded-sm text-[#3375b9] w-24 bg-[#3375b9]/50" v-else>普通用户</div>
        </template>
      </el-table-column>

      <el-table-column prop="createdate" label="创建时间" width="180" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="info" size="small" @click="getUserInfo(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteUser([scope.row.id])">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination class="mt-2" v-model:current-page="tableProps.currentPage" v-model:page-size="tableProps.pageSize"
      :page-sizes="[25, 50]" layout="total, sizes, prev, pager, next, jumper" :total="tableProps.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="userInfoVisible" title="信息修改" width="550">
    <el-form ref="formRef" :inline="true" :model="userInfo" class="demo-form-inline" :rules="rules">
      <el-form-item prop="username" label="姓名：">
        <el-input v-model="userInfo.username" clearable />
      </el-form-item>
      <el-form-item label="角色：">
        <el-select v-model="userInfo.status" style="width: 100px;">
          <el-option label="普通用户" value="1" />
          <el-option label="管理员" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item prop="loginname" label="账号：">
        <el-input v-model="userInfo.loginname" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userInfoVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserInfoChange(formRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ApiDelete, ApiPost, ApiPut } from '@/utils/Axios';
import { ElMessageBox, ElNotification, type FormInstance } from 'element-plus';
import { onBeforeMount, reactive, ref, watch } from 'vue'
const tableProps = ref({
  currentPage: 1,
  pageSize: 25,
  total: 400,
})
const selectProps = reactive({
  status: "0",
  username: "",
})
const tableData = ref([])
const multipleSelection = ref([])
const userInfo = ref({
  id: null,
  loginname: "",
  username: "",
  status: "",
})
const userInfoVisible = ref(false)
const formRef = ref<FormInstance>()

onBeforeMount(() => {
  getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
})

watch(tableProps, (newVal, oldVal) => {
  getTableData(newVal.currentPage, newVal.pageSize)
})


const getTableData = (currentPage, pageSize) => {
  ApiPost("/userInf/page", {
    page: Number(currentPage),
    pageSize: Number(pageSize),
    username: selectProps.username ? selectProps.username : null,
    status: selectProps.status === "0" ? null : Number(selectProps.status),
  }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records
      tableProps.value.total = res.data.total
    } else {
      console.log("错误=>", res.msg);
    }
  }).catch(err => {
    console.log("错误=>", err);
  })
}

const onSelect = () => {
  tableProps.value.currentPage = 1
  getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
}

const deleteUser = (userList: number[]) => {
  ElMessageBox({
    title: "警告",
    type: "warning",
    message: "确认删除用户吗？",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showCancelButton: true,
  }).then(() => {
    console.log(userList)
    ApiDelete("/userInf/delete", { ids: userList.join(",") }).then(res => {
      if(res.code === 200){
        getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
        ElNotification({
          title: "删除成功",
          type: "success",
          showClose: false,
          duration: 2000,
        })
      }else{
        ElNotification({
          title: "删除失败",
          type: "error",
          message: res.msg,
          showClose: false,
          duration: 2000,
        })
      }
    }).catch((err)=>{
      console.log("删除失败")
    })
  }).catch(()=>{
    return
  })
}

const deleteUsers = () =>{
  if(multipleSelection.value.length === 0) return
  const userList = multipleSelection.value.map(item=>item.id)
  deleteUser(userList)
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const getUserInfo = (scope) => {
  userInfo.value = { ...scope.row, status: scope.row.status.toString() }
  userInfoVisible.value = true
}

const validateLoginname = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('账号不能为空'))
  } else {
    callback()
  }
}

const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('姓名不能为空'))
  } else {
    callback()
  }
}
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  loginname: [{ validator: validateLoginname, trigger: 'blur' }],
})

const handleUserInfoChange = (formEl: FormInstance | undefined) => {
  formEl.validate(vail => {
    if (vail && userInfo.value.id) {
      ElMessageBox({
        title: "提醒",
        type: "warning",
        message: "确认修改用户信息吗？",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
      }).then(() => {
        const { id, loginname, username, status } = userInfo.value
        ApiPut("/userInf/update", { id, loginname, username, status }).then(res => {
          console.log(res)
          if (res.code === 200) {
            userInfoVisible.value = false
            getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
            ElNotification({
              title: "修改成功",
              type: "success",
              showClose: false,
              duration: 2000,
            })
          }
        })
      }).catch(() => {
        return
      })
    }
  })

}

const handleSizeChange = (val) => {
  tableProps.value = { ...tableProps.value, pageSize: val };
};
const handleCurrentChange = (val) => {
  tableProps.value = { ...tableProps.value, currentPage: val };
};
</script>